import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/animation.dart';
import 'package:collins_vocabulary/model/word.dart';
import 'package:collins_vocabulary/common/phmp3.dart';
import 'package:collins_vocabulary/components/detail.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:collins_vocabulary/model/db.dart';
import 'dart:async';

class RememberVocab extends StatefulWidget {
  SharedPreferences prefs;

  RememberVocab({Key key, this.prefs}) : super(key: key);
  @override
  RememberVocabState createState() {
    return RememberVocabState();
  }
}

class RememberVocabState extends State<RememberVocab>
    with SingleTickerProviderStateMixin {
  DBClient client;
  int currentIndex;
  bool next;
  Word currentItem;
  List list = [];
  List stuiedWords = [];
  AnimationController controller;
  Animation<Offset> animation;
  TextDirection direction;
  Future _future;

  @override
  initState() {
    super.initState();
    _future = getlist();
    controller =
        AnimationController(duration: Duration(milliseconds: 300), vsync: this);
    animation = Tween(
      begin: Offset(0.0, 0.0),
      end: Offset(1.0, 0.0),
    ).animate(CurvedAnimation(parent: controller, curve: Curves.easeInOut))
      ..addStatusListener(statusListener);
    setState(() {
      currentIndex = 0;
      next = false;
      direction = TextDirection.rtl;
    });
  }

  @override
  void dispose() {
    animation.removeStatusListener(statusListener);
    controller.dispose();
    super.dispose();
  }

  statusListener(status) {
    if (status == AnimationStatus.completed && mounted) {
      setState(() {
        if (next == true && mounted) {
          currentIndex = currentIndex + 1 == widget.prefs.getInt('count')
              ? currentIndex
              : currentIndex + 1;
          setState(() {
            next = false;
          });
        }
      });
      controller.reverse();
    }
  }

  Future<int> getLevel() async {
    client = DBClient();
    final int level = widget.prefs.getInt('level');
    return level;
  }

  Widget _getPhMp3() {
    if (widget.prefs.getBool('en_ph')) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          PhMp3(
            text: currentItem.ph_en,
            src: currentItem.ph_en_mp3,
            color: Colors.blueGrey,
            autoplay: widget.prefs.getBool('autoplay'),
          ),
          Text(
            '（英式发音）',
            style: TextStyle(
              color: Color(0xFFffc75f),
              fontSize: 12.0,
              fontWeight: FontWeight.bold,
            ),
          )
        ],
      );
    } else {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          PhMp3(
            text: currentItem.ph_am,
            src: currentItem.ph_am_mp3,
            color: Colors.blueGrey,
            autoplay: widget.prefs.getBool('autoplay'),
          ),
          Text(
            '（美式发音）',
            style: TextStyle(
              color: Color(0xFFFF5FAA),
              fontSize: 12.0,
              fontWeight: FontWeight.bold,
            ),
          )
        ],
      );
    }
  }

  Future<List> getlist() async {
    await Future.delayed(Duration(milliseconds: 300));
    final int level = await getLevel();
    List stuiedWords = await client.queryAll();
    final wholeList = await Word().getList(level);
    List lastWords;
    if (stuiedWords != null) {
      lastWords = wholeList.where((item) {
        return !stuiedWords.contains(item['word']);
      }).toList();
    } else {
      lastWords = wholeList;
    }
    int count = widget.prefs.getInt('count');
    int len = count > lastWords.length ? lastWords.length : count;
    return lastWords.sublist(0, len);
  }

  _checkIsFinish(BuildContext context, int index, bool know) async {
    if (index == widget.prefs.getInt('count')) {
      final snackBar = SnackBar(
        content: Text(
          '已完成今日学习计划',
          style: TextStyle(color: Colors.white),
          textAlign: TextAlign.center,
        ),
      );
      Scaffold.of(context).showSnackBar(snackBar);
    } else if (mounted) {
      if (know) {
        setState(() {
          direction = TextDirection.ltr;
          next = true;
        });
        await client.insert(currentItem);
      } else {
        setState(() {
          direction = TextDirection.rtl;
          next = true;
        });
      }
      controller.forward();
    }
  }

  Widget _builder(context, snapshot) {
    if (snapshot.hasData) {
      list = snapshot.data;
      currentItem = Word().getDetail(list[currentIndex]);
      return Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            padding: const EdgeInsets.only(top: 24.0, bottom: 8.0),
            child: Text(
              currentItem.text,
              style: TextStyle(
                fontSize: 40,
                fontWeight: FontWeight.bold,
                color: Color(0xFF7F8AEE),
              ),
            ),
          ),
          Expanded(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Container(
                  child: _getPhMp3(),
                ),
                Padding(padding: const EdgeInsets.only(top: 10.0)),
                Means(currentItem: currentItem, prefs: widget.prefs),
              ],
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Expanded(
                  child: Container(
                decoration: BoxDecoration(
                  border: Border(
                    right:
                        const BorderSide(width: 1.0, color: Color(0xFFF4F4F4)),
                    top: const BorderSide(width: 1.0, color: Color(0xFFF4F4F4)),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                      horizontal: 6.0, vertical: 10.0),
                  child: Center(
                    child: GestureDetector(
                      onTap: () {
                        _checkIsFinish(context, currentIndex + 1, false);
                      },
                      child: Text(
                        '不认识',
                        style: TextStyle(
                          color: Color(0xFFED1157),
                          fontSize: 13,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
              )),
              Expanded(
                  child: Container(
                decoration: BoxDecoration(
                  border: Border(
                    right:
                        const BorderSide(width: 1.0, color: Color(0xFFF4F4F4)),
                    top: const BorderSide(width: 1.0, color: Color(0xFFF4F4F4)),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 6.0,
                    vertical: 10.0,
                  ),
                  child: Center(
                    child: GestureDetector(
                      onTap: () {
                        _checkIsFinish(context, currentIndex + 1, false);
                      },
                      child: Text(
                        '模糊',
                        style: TextStyle(
                          color: Color(0xFF4999E4),
                          fontSize: 13,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                  ),
                ),
              )),
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    border: Border(
                      top: const BorderSide(
                          width: 1.0, color: Color(0xFFF4F4F4)),
                    ),
                  ),
                  child: Padding(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 6.0,
                      vertical: 10.0,
                    ),
                    child: Center(
                      child: GestureDetector(
                        onTap: () {
                          _checkIsFinish(context, currentIndex + 1, true);
                        },
                        child: Text(
                          '认识',
                          style: TextStyle(
                            color: Color(0xFF28B98B),
                            fontSize: 13,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      );
    }
    return Center(
      child: CircularProgressIndicator(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          color: Colors.white,
        ),
        child: Column(
          children: <Widget>[
            Expanded(
              child: SlideTransition(
                position: animation,
                textDirection: direction,
                child: GestureDetector(
                  child: Container(
                    margin: const EdgeInsets.all(35),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(18),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(.12),
                          offset: Offset.zero,
                          blurRadius: 15,
                          spreadRadius: 0.1,
                        )
                      ],
                    ),
                    child: FutureBuilder(
                      future: _future,
                      builder: _builder,
                      initialData: null,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
